﻿#include "hzpch.h"
#include "OrthographicCameraControll.h"
#include "SourceCode/Base/KeyCodes.h"
#include "SourceCode/Base/Input.h"

namespace Hazal
{
	COrthographicCameraControll::COrthographicCameraControll(float fAspectRatio, bool bRotation)
		:m_fAspectRatio(fAspectRatio), m_bRotation(bRotation),
		m_camera(-fAspectRatio * m_fZoomLevel, fAspectRatio* m_fZoomLevel, -m_fZoomLevel, m_fZoomLevel)
	{

	}

	void COrthographicCameraControll::OnUpdate(float fTimeSpan)
    {
		/// 设置相机移动

		if (CInput::IsKeyPressed(HZ_KEY_W))
		{
			m_cameraPos.y += m_fCameraTranslationSpeed * fTimeSpan;
		}

		if (CInput::IsKeyPressed(HZ_KEY_S))
		{
			m_cameraPos.y -= m_fCameraTranslationSpeed * fTimeSpan;
		}
		
		if (CInput::IsKeyPressed(HZ_KEY_A))
		{
			m_cameraPos.x -= m_fCameraTranslationSpeed * fTimeSpan;
		}
		
		if (CInput::IsKeyPressed(HZ_KEY_D))
		{
			m_cameraPos.x += m_fCameraTranslationSpeed * fTimeSpan;
		}

		m_fCameraTranslationSpeed = m_fZoomLevel;

		m_camera.SetPosition(m_cameraPos);

		/// 设置相机旋转
		if (m_bRotation)
		{
			if (CInput::IsKeyPressed(HZ_KEY_Q))
			{
				m_fRotationOffset += m_fCameraRotationSpeed * fTimeSpan;
				m_camera.SetRotation(m_fRotationOffset);
			}

			if (CInput::IsKeyPressed(HZ_KEY_E))
			{
				m_fRotationOffset -= m_fCameraRotationSpeed * fTimeSpan;
				m_camera.SetRotation(m_fRotationOffset);
			}
		}
    }

    void COrthographicCameraControll::OnEvent(CEvent& e)
    {
        CEventDispatcher dispatcher(e);
    
        dispatcher.Dispatch<CMouseScrolledEvent>(HZ_BIND_EVENT_FN(COrthographicCameraControll::OnMouseScrolled));
        dispatcher.Dispatch<CWindowResizeEvent>(HZ_BIND_EVENT_FN(COrthographicCameraControll::OnWindowResized));
    }

	void COrthographicCameraControll::OnResize(float fWidth, float fHeight)
	{
		m_fAspectRatio = fWidth / fHeight;
		m_camera.SetProjectionMatrix(-m_fAspectRatio * m_fZoomLevel, m_fAspectRatio * m_fZoomLevel, -m_fZoomLevel, m_fZoomLevel);
	}

    bool COrthographicCameraControll::OnMouseScrolled(CMouseScrolledEvent& e)
    {
		m_fZoomLevel -= e.GetYOffset() * 0.25f;
		m_fZoomLevel = std::max(m_fZoomLevel, 0.25f);

		m_camera.SetProjectionMatrix(-m_fAspectRatio * m_fZoomLevel, m_fAspectRatio * m_fZoomLevel, -m_fZoomLevel, m_fZoomLevel);

        return false;
    }
	
	bool COrthographicCameraControll::OnWindowResized(CWindowResizeEvent& e)
    {
		OnResize((float)e.GetWidth(), (float)e.GetHeight());

        return false;
    }

}